package com.leenmvc.core.security.controller;

import com.leenmvc.core.annotation.Note;
import com.leenmvc.core.base.BaseController;
import com.leenmvc.core.security.entity.dynamic.JavaScript;
import com.leenmvc.core.utils.dynamic.MyClassLoader;
import com.leenmvc.core.web.Result;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态
 */
@RestController
@RequestMapping("system/javaScript")
public class JavaScriptController extends BaseController<JavaScript> {

    private final static Logger logger = LoggerFactory.getLogger(JavaScriptController.class);

    private static Map<String, HashMap<Object, Method>> methodMap = new HashedMap();

    /**
     * 对数据库中指定ID的记录进行执行
     *
     * @param id 命令的记录id
     * @param command 指令 1-运行 2-执行
     * @return
     */
    @RequestMapping("execute")
    @Note("执行存储在数据库中的java脚本，通过类加载器的形式动态执行功能")
    public Result execute(@RequestParam(required = true) Long id, @RequestParam(required = true) Integer command) {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        JavaScript o = get(id);
        switch (o.getType()) {
            case 1: // 执行java
                try {
                    if(command == 1) {
                        MyClassLoader myClassLoader = new MyClassLoader();
                        methodMap.put(o.getScript(), myClassLoader.loadingJavaStrAndInvoke(o.getScript(), o.getMethod()));
                        o.setStatus(1);
                        if (update(o)) {
                            return new Result();
                        };
                    } else if (command == 0) {
                        HashMap<Object, Method> objectMethodHashMap = methodMap.get(o.getScript());
                        for(Object obj: objectMethodHashMap.keySet()) {
                            objectMethodHashMap.get(obj).invoke(obj);
                        }
                        o.setStatus(0);
                        if (update(o)) {
                            return new Result();
                        };
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    return new Result().error(e.getMessage());
                }
                break;
            case 2: // 执行shell脚本

                break;
        }
        return new Result().info("失败！");
    }

    /**
     * 执行shell脚本的方法
     *
     */
    public void executeShell() {


    }

}
